package com.company.algo.niuke;

import java.util.*;


public class LRU2 {
    /**
     * lru design
     *
     * @param operators int整型二维数组 the ops
     * @param k         int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU(int[][] operators, int k) {
        // write code here
        ArrayList<Integer> list = new ArrayList<>();
        LRUCache lru = new LRUCache(k);
        for (int[] opt : operators) {
            if (opt[0] == 1) {
                lru.put(opt[1], opt[2]);
            } else {
                list.add(lru.get(opt[1]));
            }
        }
        int[] res = new int[list.size()];
        int i = 0;
        for (int val : list) {
            res[i] = list.get(i);
            i++;
        }
        return res;
    }


    public static void main(String[] args) {
        LRU2 Main = new LRU2();
        int[][] operators = new int[6][];
        operators[0] = new int[]{1, 1, 1};
        operators[1] = new int[]{1, 2, 2};
        operators[2] = new int[]{1, 3, 2};
        operators[3] = new int[]{2, 1};
        operators[4] = new int[]{1, 4, 4};
        operators[5] = new int[]{2, 2};
        int k = 3;
        System.out.println(Arrays.toString(Main.LRU(operators, k)));
    }
}

//设置LRU缓存结构
class LRUCache {
    int cap;
    LinkedHashMap<Integer, Integer> cache = new LinkedHashMap<>();

    public LRUCache(int capactity) {
        this.cap = capactity;
    }

    // 将key变为最近使用
    private void makeRecently(int key) {
        int val = cache.get(key);
        //删除key，重新插入到队尾
        cache.remove(key);
        cache.put(key, val);
    }


    //获取值
    public int get(int key) {
        if (!cache.containsKey(key)) {
            return -1;
        }
        //将这个key变为最近使用的
        makeRecently(key);
        return cache.get(key);
    }

    //存进值
    public void put(int key, int val) {
        if (cache.containsKey(key)) {
            cache.put(key, val);
            //设置为最近使用
            makeRecently(key);
            return;
        }

        //超出缓存的大小
        if (cache.size() >= this.cap) {
            //拿到链表头部的key（其最久未使用的key）
            int oldestKet = cache.keySet().iterator().next();
            cache.remove(oldestKet);
        }
        //将新的key添加到链表尾部
        cache.put(key, val);
    }

}
